package me.derek.rs.service.impl;

import me.derek.rs.model.Customer;
import me.derek.rs.service.CustomerService;
import io.swagger.annotations.Api;

import javax.ws.rs.core.Response;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Api("/customer")
public class CustomerServiceImpl implements CustomerService {

    Map<Long, Customer> customers = new HashMap<Long, Customer>();

    public CustomerServiceImpl() {
        init();
    }

    public Collection getCustomers() {
        System.out.println("---- getCustomers-----");
        return customers.values();
    }

    public Response deleteCustomers() {
        System.out.println("---- deleteCustomers-----");
        Response r;
        customers.clear();
        if(!customers.isEmpty()){
            r = Response.status(500).build();
        }else{
            r = Response.ok().build();
        }
        return r;
    }

    public Customer getCustomer(Long id) {
        System.out.println("---- getCustomer-----");
        return customers.get(id);
    }

    public Response updateCustomer(Customer customer){
        System.out.println("---- updateCustomer-----");
        Customer existedCustomer = customers.get(customer.getId());
        Response r;
        if(existedCustomer == null){
            r = Response.status(404).build();
        }else{
            existedCustomer.setName(customer.getName());
            r = Response.ok().build();
        }
        return r;
    }

    public Response addCustomer(Customer customer) {
        System.out.println("---- addCustomer-----");
        Customer existedCustomer = customers.get(customer.getId());
        Response r;
        if(existedCustomer == null){
            customers.put(customer.getId(), customer);
            r = Response.ok().build();
        }else{
            r = Response.status(400).build();
        }
        return r;
    }

    public Response deleteCustomer(Long id) {
        System.out.println("---- deleteCustomer-----");
        Customer existedCustomer = customers.get(id);
        Response r;
        if(existedCustomer == null){
            r = Response.status(404).build();
        }else{
            customers.remove(id);
            r = Response.ok().build();
        }
        return r;
    }

    final void init() {
        Customer c = new Customer();
        c.setName("John");
        c.setId(123);
        customers.put(c.getId(), c);
    }
}
